package edu.vt.ece.rt;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import edu.vt.ece.rt.benchmark.bank.Benchmark;
import edu.vt.ece.rt.quorum.Cluster;
import edu.vt.ece.rt.quorum.ClustersManager;
import edu.vt.ece.rt.quorum.util.Names;
import edu.vt.ece.rt.quorum.util.WaitObject;
import edu.vt.ece.rt.util.Logger.Logger;

/*
 * Required to Initiate all the Components
 * @author Sudhanshu
 */
public class QR {
	/*
	 * Node Status used to simulate node failure
	 */
	static boolean muted = false;
	public static int script = 1;
	/*
	 * Create base Cluster
	 */
	public static void init() throws Exception{
		//Load Configuration
		loadConfig();
		Logger.debug("Initiating QR");
		//Create Base cluster
		Thread.sleep((5000L)* (ClustersManager.baseClusterId + 1));

		Cluster cluster = new Cluster();
		cluster.init();
		Logger.debug("Channel Initiated");
		cluster.waitForCluster();
		cluster.createTree(Integer.getInteger(Names.degree));
		//Register the cluster so that other components can access that cluster
		ClustersManager.registerCluster(Names.base, cluster);
//		Thread.sleep(1000);		//To make sure all base clusters are registered
		
		//Set exit point for node
//		ClustersManager.waitTillDone = new WaitObject(cluster.getReplyCount());
		
	}
	
	public static void loadConfig() throws IOException {
		System.out.println("Script value is "+script);
		if (script == 1) {
			return;
		}
		
		Properties defaults = new Properties();
		defaults.load(QR.class.getResourceAsStream("default.conf"));

		// load Quorum properties
		for (Object key : defaults.keySet())
			System.setProperty(key.toString(),System.getProperty(key.toString(), defaults.getProperty(key.toString())));
	}

	public static void close() {
		Collection<Cluster> l = ClustersManager.getClusterMap().values();
		
		for(Cluster c: l)
			c.close();
	}
	
	public static boolean getQRStatus(){
		return muted;
	}
	
	public static void setQRStatus(boolean s){
		muted = s;
	}
}
